from PyQt5.QtCore import Qt, QThread
import ProceDataLayer as PDL
import time
from commonData import Data as data
import os, re
from openpyxl import load_workbook
from openpyxl.utils import get_column_letter
from xlrd import open_workbook

class MyThread(QThread):
    # finsh_signal = pyqtSignal(dict)  # 设置一个dict的信号，内部是缺失的站点数据
    def __init__(self):
        super(MyThread, self).__init__()

    def run(self):
        print("处理中...")
        # profiiler = Profiler()
        # profiiler.start()

        startTime = time.time()

        print("="*10, "读取文件夹内所有excel中", "="*10)
        if len(data.dict_of_all_excel) == 0:
            data.years = []  # 更新年份
            for file in os.listdir(data.in_folder):
                temp = re.findall(r'(\w+)_(\d{4})', file)[0]  # 获取type和year
                data.TYPE, year = temp[0], temp[1]
                data.years.append(year)
            data.years = sorted(set(data.years))  # 给year进行排序，使years内部按照从小到大排序。
            for file in os.listdir(data.in_folder):
                if file not in data.dict_of_all_excel.keys():
                    print("读取{}..".format(file))
                    data.dict_of_all_excel[file] = load_workbook(data.in_folder + "\\" + file)  # file -- dict 字典
        else:
            print("文件已读取！\n")
        if data.user_value:
            print("="*9, "读取用户自定义pd、py中", "="*9)
            wb = load_workbook(data.pdpy_excel_file)
            ws = wb[wb.sheetnames[0]]
            oneLine = [x.value for x in ws["A1:G1"][0]]
            pd_index, py_index = get_column_letter(oneLine.index('pduser')+1), get_column_letter(oneLine.index('pyuser')+1)
            for row in range(2, ws.max_row + 1):
                row = str(row)
                station = ws['A' + row].value
                pd_v, py_v = ws[pd_index + row].value, ws[py_index + row].value
                if station != None:
                    if station not in data.user_pdpy_data.keys():
                        data.user_pdpy_data[station] = [None, None]
                    data.user_pdpy_data[station][0],  data.user_pdpy_data[station][1] = pd_v, py_v

        # 如果是用户自定义的，则不需要计算pd py的值，直接进行计算即可。
        if data.recent == '北师大模型' and data.user_value == False:  # 如果是北师大模型，且非用户自定义，且py内值为0的情况下进行计算，否则默认其中有值
            PDL.Data().start_cal_pd_and_py()  # 则要计算
        else:
            PDL.Data().finally_cal()

        print("处理完毕,用时%.2f秒,%.2f分钟" % (time.time() - startTime, (time.time() - startTime) / 60))
